<template>
  <ex-dialog width="1200px" class="ex-diolog" :title="title" :visible="visible" :close-on-click-modal="false"
    @closeDialog="handleClose">
    <div class="main" v-loading="loading">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm"
        :disabled="disabled">
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否上架：" prop="status">
              <el-switch v-model="ruleForm.status" active-value="2" inactive-value="1" active-text="上架"
                inactive-text="下架">
                </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称：" prop="name">
              <el-input class="shopName" placeholder="请输入" v-model="ruleForm.name" maxlength="50" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="商品图片:" prop="imgList" >
              <el-checkbox-group v-model="ruleForm.imgList" v-show="false"></el-checkbox-group>
              <ImageUploadMoreOldUrl :limit="6" :fileSize="2" v-model="ruleForm.imgList" :showTipInfo="true"> 
                <div slot="showTipInfo">建议上传尺寸为<span style="color: #f56c6c">375*225</span>的图片，大小不超过<span style="color: #f56c6c">2MB</span>（最多上传 6 张）</div>
              </ImageUploadMoreOldUrl>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品库存：" :prop="pathType == 'edit'?'':'total'">
              <el-input placeholder="请输入" v-model="ruleForm.total"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4" v-if="pathType == 'edit'">
            <div class="stockNum">剩余库存: {{ ruleForm.usable?ruleForm.usable:0}}</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item label="支付类型：" prop="payType">
              <el-select v-model="ruleForm.payType" placeholder="请选择积分类型" size="small">
                <el-option v-for="item in payTypeList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="ruleForm.payType !=''">
            <el-form-item label="" prop="payAmount" label-width="20px">
              <el-input placeholder="请输入支付金额" v-model="ruleForm.payAmount"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="是否限购：" required >
              <el-switch v-model="ruleForm.limitBuyType" active-value="1" inactive-value="2" active-text="开启"
                inactive-text="关闭">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="ruleForm.limitBuyType == 1">
            <el-form-item label="" label-width="0" prop="limitBuyNum">
              <el-input placeholder="请输入限制兑换数量" v-model="ruleForm.limitBuyNum"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序：" prop="sort">
              <el-input v-model="ruleForm.sort" placeholder="请输入" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="兑换规则：" required  style="margin-bottom: 10px;">
              <el-switch v-model="ruleForm.exchangeRuleType" active-value="1" inactive-value="2" active-text="开启"
                inactive-text="关闭">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="ruleForm.exchangeRuleType == 1">
            <el-form-item label="" prop="exchangeRule">
              <el-input type="textarea" maxlength="1000" placeholder="请输入兑换规则" v-model="ruleForm.exchangeRule" show-word-limit
                :autosize="{ minRows: 6 }">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="兑换详情：" required style="margin-bottom: 10px;">
              <el-switch v-model="ruleForm.exchangeDetailType" active-value="1" inactive-value="2" active-text="开启"
                inactive-text="关闭">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="20" v-if="ruleForm.exchangeDetailType == 1">
            <el-form-item label="" prop="exchangeDetail">
              <WangEditor :value.sync="ruleForm.exchangeDetail"  style="width:95%;" ></WangEditor>
            </el-form-item>
          </el-col>
        </el-row>
        </el-form>
        </div>
        <div class="button_box">
          <el-button type="primary" :loading="AgreeLoading" @click="submitForm('ruleForm')">保存提交</el-button>
          <el-button @click="handleClose">关闭</el-button>
      </div>
  </ex-dialog>
</template>

<script>
// api
import {
  merchantExchangeGoodsV1Add,
  merchantExchangeGoodsV1Edit,
  merchantExchangeGoodsV1Detail,
} from "@/api/consumeMiningManagement/merchantRedemptionManagement";
import WangEditor from '@/components/WangEditor'
import ImageUploadMoreOldUrl from "@/components/ImageUploadMoreOldUrl"
export default {
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  components: {
    WangEditor,
    ImageUploadMoreOldUrl
  },
  data() {
    var checkincentiveAmount = (rule, value, callback) => {
      let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (!value) {
          return callback(new Error("请输入支付金额"));
        } else if (regNumber.test(value) == false) {
          return callback(new Error("请填写大于0且最多保留两位小数的数值"));
        } else {
          return callback();
        }
    };
     var checklimitBuy = (rule, value, callback) => {
      let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
        if (value === '') {
          console.log('value99999',value)
          return callback(new Error("请输入限制兑换数量"));
        } else if (regNumber.test(value) == false) {
          return callback(new Error("请输入大于0的整数"));
        } else {
          return callback();
        }
    };
    var checksort = (rule, value, callback) => {
      let regNumber = /^(?:0|\-?[1-9]\d*)$/; //只能输入整数（含负数）
        if (value === '') {
          return callback(new Error("请输入排序号"));
        } else if (regNumber.test(value) == false) {
          return callback(new Error("只能输入整数"));
        } else {
          return callback();
        }
    };
    return {
      labelWidth: "150px",
      inputWidth: "420px",
      title: "新增兑换商品",
      loading: false,
      disabled: false,
      AgreeLoading: false,
      residueStock:0,//商品库存剩余数量
      ruleForm: {
        status:'2',//商品状态 1 下架 2 上架
        name: "", //商品名称
        imgList:[],//商品图片
        total: "", //商品库存
        payType: "", //支付类型
        payAmount: "", //支付金额
        limitBuyType: "1", //限购类型 1 开启 2 关闭
        limitBuyNum:"",//限购数量
        sort: "", //排序
        exchangeRule: "", //兑换规则
        exchangeRuleType: "1", //兑换规则类型 1 开启 2 关闭
        exchangeDetail: "", //兑换详情
        exchangeDetailType: "1", //兑换详情类型 1 开启 2 关闭
      },
      payTypeList:[
        {id:'1',value:'商户积分'}
      ],
      rules: {
        status: [
          { required: true, message: "请选择上架状态", trigger: ["change"] }
        ],
        name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        imgList: [
          { required: true, message: "请上传商品图片", trigger: ["change"] }
        ],
        total: [
          { required: true, message: "请输入商品库存", trigger: "bulr" },
          { pattern: /^\+?[0-9][0-9]*$/, message: '请输入大于等于0的正整数' }
        ],
        payType: [
          { required: true, message: "请选择支付类型", trigger:  ["change", "bulr"] }
        ],
        payAmount: [
          { validator: checkincentiveAmount, required: true, trigger: ["change", "bulr"] }
        ],
        limitBuyNum: [
        { validator: checklimitBuy, required: true, trigger: ["change", "bulr"] }
        ],
        sort: [
          { validator: checksort, required: true, trigger: ["change", "bulr"] }
        ],
        exchangeRule: [
          { required: true, message: "请输入兑换规则", trigger: "bulr"}
        ],
        exchangeDetail: [
          { required: true, message: "请输入兑换详情", trigger: "bulr"}
        ],
      },

    };
  },
  created() {
    if (this.pathType == 'edit') {
      this.title = '编辑兑换商品'
      this.ruleForm.id = this.id
      this.getInfo()
    }
  },
  methods: {
    //获取详情
    getInfo() {
      var id = this.ruleForm.id
      merchantExchangeGoodsV1Detail(id).then(res => {
        this.ruleForm = Object.assign(this.ruleForm, res.result) 
        this.ruleForm.imgList = this.ruleForm.imgList.toString()
        console.log('this.ruleForm6669', this.ruleForm)
      })
    },

    //取消
    handleClose(formName) {
      this.$emit("update:visible", false);
    },
    // 保存提交
    submitForm(formName) {
      //创建确定
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.AgreeLoading = true
          var data = {
            ...this.ruleForm
          }
          data.imgList = data.imgList.split(',')
          if (this.pathType == 'add') {
            merchantExchangeGoodsV1Add(data).then(res => {
              setTimeout(() => {
                this.handleClose()
                this.$message.success('创建成功')
                this.$emit('success')
                this.AgreeLoading = false
              }, 1000);
            }).catch(() => {
              this.AgreeLoading = false
            })
          } else if (this.pathType == 'edit') {
            merchantExchangeGoodsV1Edit(data).then(res => {
              setTimeout(() => {
                this.handleClose()
                this.$message.success('修改成功')
                this.$emit('success')
                this.AgreeLoading = false
              }, 1000);
            }).catch(() => {
              this.AgreeLoading = false
            })
          }

        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

  }
};
</script>

<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
    padding: 0 !important;
  }

  ::v-deep .ex--dialog--main {
    padding: 10px 20px !important;
  }
}

.el-select {
  width: 100%;
}

.main {
  padding: 20px 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
  padding: 10px 0;
  border-bottom: 4px solid #1890ff;
  margin-bottom: 20px;
}

.richText {
  border: 1px solid #ccc;
  line-height: normal;
}

.stockNum {
  display: flex;
  justify-content: center;
  padding-top: 10px;
}

.button_box {
  display: flex;
  justify-content: center;
}

.equityImgBox {
  width: 100%;
  display: flex;
  justify-content: center;
}

.equityImgBox img {
  width: 120px;
  height: 120px;
}

.el-form-item {
  margin-bottom: 32px;
}
::v-deep  .shopName .el-input__suffix{
  right: -45px;
}
</style>
